/**********************************************
 * Copyright (c) 2022
 * All rights reserved.
 *
 * 文件名称：get_temp.c
 * 摘 要：ds18b20传感器获取温度
 *
 * 当前版本：1.0
 * 作 者：任慧
 * 完成日期：2022年7月23日
 *
 * ********************************************/

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

#include "zlog.h"

int get_temp(float *T)
{

	char             w1_path[128] = "/sys/bus/w1/devices/";
	char             buf[128];
	DIR             *drip = NULL;
	struct dirent   *ptr = NULL;
	int              found = 0;
	int              fd;
	char            *temp = NULL;
	zlog_category_t            *c = NULL;       //zlog

	drip = opendir(w1_path);
	memset(buf, 0, sizeof(buf));

	c = zlog_get_category("my_log");
        if (!c)
        {
                printf("Get log failure\n");
                zlog_fini();
                return -2;
        }

	if (!drip)
	{
		zlog_error(c,"open floder %s failure:%s", w1_path, strerror(errno));
		return -1;
	}

	while ((ptr = readdir(drip)) != NULL)
	{
		if (strstr(ptr->d_name, "28-"))
		{
			strncat(w1_path, ptr->d_name, sizeof(w1_path)-strlen(w1_path));
			strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));
			found = 1;
		}
	}
	closedir(drip);
	if (!found)
	{
		zlog_error(c,"can not find ds18b20 chipset!:%s",strerror(errno));
		return -1;
	}
	
	fd = open(w1_path, O_RDONLY);
	if (fd < 0)
	{
		zlog_error(c,"open filure failure:%s", strerror(errno));
		return -1;
	}
	if (read(fd, buf, sizeof(buf)) < 0)
	{
		zlog_error(c,"read data from fd = %d failure:%s", fd, strerror(errno));
		close(fd);
		return -1;
	}
	temp = strstr(buf, "t=");
	temp = temp+2;
	*T = atof(temp)/1000.0;
	close(fd);
	return 0;
}
